# -*- coding: utf-8 -*-
# @Author  : longbhu
# @Time    : 2025/7/21 14:40
# @Function:
from sqlalchemy import event
from routes import db  # 数据库实例
from typing import List
from models.gep_model import GepResult  # GEP 参数和结果模型
from models.user_model import RegulationData
from models.vep_model import VepResult, VepParameter
from flask import request, jsonify
from utils.redis import cache_result, redis_client_instance

# 定义允许的 gepTown 列表
ALLOWED_TOWNS = [
    "河口镇", "湖坊镇", "石塘镇", "稼轩乡", "紫溪乡", "英将乡", "虹桥乡",
    "陈坊乡", "鹅湖镇", "天柱山乡", "武夷山镇", "太源畲族乡", "篁碧畲族乡",
    "新滩乡", "永平镇", "汪二镇", "葛仙山镇", "青溪办事处"
]

ALLOWED_VEP_NAMES = [
    "葛仙村国际度假区-1期", "葛仙村国际度假区-2期", "明清古镇", "河红茶", "红芽芋"
]

# 创建全局的 HomepageService 实例，用于事件处理
homepage_service_instance = None

def clear_cache_for_year_district_global(year: int, district: str):
    """全局函数：清除特定年份和地区的所有相关缓存"""
    cache_patterns = [
        f"get_homepage_data_bar01:year={year}:district={district}",
        f"get_homepage_data_pie01:year={year}:district={district}",
        f"get_homepage_data_bar02:year={year}:district={district}",
        f"get_homepage_data_bar03:year={year}:district={district}",
        f"get_homepage_data_pie02:year={year}:district={district}",
        f"get_homepage_data_form01:year={year}:district={district}",
        f"get_homepage_data_form02:year={year}:district={district}"
    ]

    try:
        if redis_client_instance.client:
            deleted_count = 0
            for pattern in cache_patterns:
                # 检查键是否存在
                if redis_client_instance.exists(pattern):
                    # 删除键并检查返回值
                    result = redis_client_instance.delete(pattern)
                    if result > 0:
                        deleted_count += 1
                        print(f"Cache cleared successfully: {pattern}")
                    else:
                        print(f"Failed to clear cache: {pattern}")
                else:
                    print(f"Cache key does not exist: {pattern}")

            print(f"Successfully deleted {deleted_count}/{len(cache_patterns)} cache entries")
            return deleted_count
        else:
            print("Redis client is not initialized")
            return 0
    except Exception as e:
        print(f"Error clearing cache: {e}")
        return 0

def clear_all_homepage_cache_global():
    """全局函数：清除所有 homepage 相关缓存"""
    try:
        if redis_client_instance.client:
            # 查找所有 homepage 相关的缓存键
            keys = redis_client_instance.keys("get_homepage_data_*")
            if keys:
                # 删除所有匹配的键
                deleted_count = redis_client_instance.delete(*keys)
                print(f"Cleared {deleted_count}/{len(keys)} cache entries")
                return deleted_count
            else:
                print("No homepage cache keys found")
                return 0
        else:
            print("Redis client is not initialized")
            return 0
    except Exception as e:
        print(f"Error clearing all cache: {e}")
        return 0


def clear_related_cache(mapper, connection, target):
    """当数据发生变化时清除相关缓存"""
    try:
        print(f"Clearing cache for {target.__tablename__} with id {target}")
        # 根据变更的数据确定需要清除的缓存
        if hasattr(target, 'year') and hasattr(target, 'gepDistrict'):
            deleted_count = clear_cache_for_year_district_global(target.year, target.gepDistrict)
            print(f"Cleared {deleted_count} cache entries for gep data")
        elif hasattr(target, 'year') and hasattr(target, 'vepDistrict'):
            deleted_count = clear_cache_for_year_district_global(target.year, target.vepDistrict)
            print(f"Cleared {deleted_count} cache entries for vep data")
    except Exception as e:
        print(f"Error in cache clearing event: {e}")


class HomepageService:
    def __init__(self):
        global homepage_service_instance
        homepage_service_instance = self

    def _generate_cache_key(self, func_name, year, district):
        """生成缓存键"""
        return f"{func_name}:year={year}:district={district}"

    def clear_cache_for_year_district(self, year: int, district: str):
        """清除特定年份和地区的所有相关缓存"""
        clear_cache_for_year_district_global(year, district)

    def clear_all_homepage_cache(self):
        """清除所有 homepage 相关缓存"""
        clear_all_homepage_cache_global()

    # 使用装饰器
    @cache_result(expiration=86400)
    def get_homepage_data_bar01(self, year: int, district: str) :
        record_bar01 = GepResult.query.filter(GepResult.year == year, GepResult.gepDistrict == district, GepResult.gepTown.in_(ALLOWED_TOWNS)).all()

        match_data = [
            {
                "name": r.gepTown,
                "value": r.gepResult
            } for r in record_bar01
        ]
        return match_data
    @cache_result(expiration=86400)
    def get_homepage_data_pie01(self, year: int, district: str):
        # 获取饼图数据 铅山县的gep的三部分
        data_pie01 = GepResult.query.filter(GepResult.year == year, GepResult.gepDistrict == district,
                                            GepResult.gepTown == '总计').first()
        data_pie02 = RegulationData.query.filter(RegulationData.year == year, RegulationData.gepDistrict == district,
                                                 RegulationData.gepTown == '总计').first()

        # 增加空值检查
        if not data_pie01 or not data_pie02:
            return []  # 或者返回适当的默认值

        match_data = [
            {
                "name": "物质产品",
                "value": data_pie01.materialSupplyValue + data_pie01.cleanEnergyValue + data_pie01.waterResourcesValue
            },
            {
                "name": "调节服务",
                "value": data_pie02.outWaterSourceConservation + data_pie02.outSoilConservation + data_pie02.outAirPurification +
                         data_pie02.outWaterPurification + data_pie02.outCarbonSequestration + data_pie02.outClimateRegulation +
                         data_pie02.outCalcFloodRegulation + data_pie02.outCalcBiodiversityProtection + data_pie02.outCalcNoiseReduced
            },
            {
                "name": "文化服务",
                "value": data_pie01.tourismHealthValue + data_pie01.leisureRecreationValue + data_pie01.landscapeAppreciationValue
            }
        ]
        return match_data
    @cache_result(expiration=86400)
    def get_homepage_data_bar02(self, year: int, district: str):
        # 使用 join 查询确保 GepResult 和 RegulationData 按 gepTown 对应
        joined_data = db.session.query(GepResult, RegulationData).join(
            RegulationData,
            (GepResult.gepTown == RegulationData.gepTown) &
            (GepResult.year == RegulationData.year) &
            (GepResult.gepDistrict == RegulationData.gepDistrict)
        ).filter(
            GepResult.year == year,
            GepResult.gepDistrict == district,
            GepResult.gepTown.in_(ALLOWED_TOWNS)
        ).all()

        # 合并或处理 data_01 和 data_02 的逻辑
        match_data = [
            {
                "name": gep_result.gepTown,
                "value1": gep_result.materialSupplyValue + gep_result.cleanEnergyValue + gep_result.waterResourcesValue,
                "value2": regulation_data.outWaterSourceConservation + regulation_data.outSoilConservation + regulation_data.outAirPurification +
                          regulation_data.outWaterPurification + regulation_data.outCarbonSequestration + regulation_data.outClimateRegulation +
                          regulation_data.outCalcFloodRegulation + regulation_data.outCalcBiodiversityProtection + regulation_data.outCalcNoiseReduced,
                "value3": gep_result.tourismHealthValue + gep_result.leisureRecreationValue + gep_result.landscapeAppreciationValue
            }
            for gep_result, regulation_data in joined_data
        ]
        return match_data
    @cache_result(expiration=86400)
    def get_homepage_data_bar03(self, year: int, district: str):
        # 使用 join 查询确保 GepResult 和 RegulationData 按 gepTown 对应
        joined_data = db.session.query(GepResult, RegulationData).join(
            RegulationData,
            (GepResult.gepTown == RegulationData.gepTown) &
            (GepResult.year == RegulationData.year) &
            (GepResult.gepDistrict == RegulationData.gepDistrict)
        ).filter(
            GepResult.year == year,
            GepResult.gepDistrict == district,
            GepResult.gepTown.in_(ALLOWED_TOWNS)
        ).all()

        # 合并或处理 data_01 和 data_02 的逻辑
        match_data = [
            {
                "towns": [
                    {
                        "name": gep_result.gepTown,
                        "data": [
                            {
                                "name": "农林牧渔",
                                "value": gep_result.materialSupplyValue
                            },
                            {
                                "name": "生态能源",
                                "value": gep_result.cleanEnergyValue
                            },
                            {
                                "name": "水资源",
                                "value": gep_result.waterResourcesValue
                            },
                            {
                                "name": "水源涵养",
                                "value": regulation_data.outWaterSourceConservation
                            },
                            {
                                "name": "土壤保持",
                                "value": regulation_data.outSoilConservation
                            },
                            {
                                "name": "空气净化",
                                "value": regulation_data.outAirPurification
                            },
                            {
                                "name": "水质净化",
                                "value": regulation_data.outWaterPurification
                            },
                            {
                                "name": "固碳价值",
                                "value": regulation_data.outCarbonSequestration
                            },
                            {
                                "name": "气候调节",
                                "value": regulation_data.outClimateRegulation
                            },
                            {
                                "name": "洪水调蓄",
                                "value": regulation_data.outCalcFloodRegulation
                            },
                            {
                                "name": "生物多样性保护",
                                "value": regulation_data.outCalcBiodiversityProtection
                            },
                            {
                                "name": "噪音消减",
                                "value": regulation_data.outCalcNoiseReduced
                            },
                            {
                                "name": "旅游康养",
                                "value": gep_result.tourismHealthValue
                            },
                            {
                                "name": "休闲游憩",
                                "value": gep_result.leisureRecreationValue
                            },
                            {
                                "name": "景观增值",
                                "value": gep_result.landscapeAppreciationValue
                            },
                        ]
                    } for gep_result, regulation_data in joined_data
                ]
            }
        ]
        return match_data
    @cache_result(expiration=86400)
    def get_homepage_data_pie02(self, year: int, district: str):
        # 获取饼图数据 铅山县的gep的三部分
        data_pie02 = VepResult.query.filter(VepResult.year == year, VepResult.vepDistrict == district,
                                            VepResult.vepName.in_(ALLOWED_VEP_NAMES)).all()
        match_data = [
            {
                "name": r.vepName,
                "data": [
                    {
                        "name": "物质产品",
                        "value": r.provisioningServices
                    },
                    {
                        "name": "调节服务",
                        "value": r.regulatingServices
                    },
                    {
                        "name": "文化服务",
                        "value": r.culturalServices
                    },
                    {
                        "name": "总计",
                        "value": r.provisioningServices + r.regulatingServices + r.culturalServices
                    }
                ]
            }for r in data_pie02
        ]
        return match_data
    @cache_result(expiration=86400)
    def get_homepage_data_form01(self, year: int, district: str):
        # 使用 join 查询确保 VepParameter 和 VepResult 按 vepName 对应
        joined_data = db.session.query(VepParameter, VepResult).join(
            VepResult,
            (VepParameter.vepName == VepResult.vepName) &
            (VepParameter.year == VepResult.year) &
            (VepParameter.vepDistrict == VepResult.vepDistrict)
        ).filter(
            VepParameter.year == year,
            VepParameter.vepDistrict == district,
            VepParameter.vepName.in_(ALLOWED_VEP_NAMES)
        ).all()

        match_data = [
            {
                "name": param.vepName,
                "area": param.projectArea,
                "vep": result.provisioningServices + result.regulatingServices + result.culturalServices
            }
            for param, result in joined_data
        ]
        return match_data
    @cache_result(expiration=86400)
    def get_homepage_data_form02(self, year: int, district: str):
        # 使用 join 查询确保 VepParameter 和 VepResult 按 vepName 对应
        joined_data = db.session.query(VepParameter, VepResult).join(
            VepResult,
            (VepParameter.vepName == VepResult.vepName) &
            (VepParameter.year == VepResult.year) &
            (VepParameter.vepDistrict == VepResult.vepDistrict)
        ).filter(
            VepParameter.year == year,
            VepParameter.vepDistrict == district,
            VepParameter.vepName.in_(ALLOWED_VEP_NAMES)
        ).all()

        match_data = [
            {
                "name": param.vepName,
                "area": param.projectArea,
                "vepValue": result.provisioningServices + result.regulatingServices + result.culturalServices,
                "materialSupply": result.provisioningServices,
                "regulatingService": result.regulatingServices,
                "culturalService": result.culturalServices,
            }
            for param, result in joined_data
        ]
        # for param, result in joined_data:
            # print("param:", param.vepName, param.projectArea)
            # print("result:", result.vepName, result.provisioningServices, result.regulatingServices, result.culturalServices)
        return match_data

# 在类定义后注册事件监听器
event.listen(GepResult, 'after_insert', clear_related_cache)
event.listen(GepResult, 'after_update', clear_related_cache)
event.listen(GepResult, 'after_delete', clear_related_cache)

event.listen(RegulationData, 'after_insert', clear_related_cache)
event.listen(RegulationData, 'after_update', clear_related_cache)
event.listen(RegulationData, 'after_delete', clear_related_cache)

event.listen(VepResult, 'after_insert', clear_related_cache)
event.listen(VepResult, 'after_update', clear_related_cache)
event.listen(VepResult, 'after_delete', clear_related_cache)

event.listen(VepParameter, 'after_insert', clear_related_cache)
event.listen(VepParameter, 'after_update', clear_related_cache)
event.listen(VepParameter, 'after_delete', clear_related_cache)

# 创建 HomepageService 实例
homepage_service = HomepageService()